var logger = require('./lib/log'), 
	fs = require('fs'),
    path = require('path'),
	_ = require('underscore');

String.prototype.endWith = function(oString){  
	var reg = new RegExp(oString+"$");  
	return reg.test(this);
}  

module.exports = function (app,config) {

	function _load (_path){
		fs.readdirSync(_path).forEach(function(file,index){
			var current = _path + path.sep + file;
			//console.log(current,index,222);
			//console.log(current);
			var stat = fs.lstatSync(current);
			if (!stat.isDirectory()){
				if(!file.endWith('.js')){
					return true;
				}
				//console.log(logger);
				var mappings = require(current).mappings;
				logger.debug('actions',current.replace(__dirname,''),'loaded.');
				if(mappings){
					//console.log(typeof {},_.isArray(mappings));
					if(_.isArray(mappings)){
						_.each(mappings,function(item){
							(app[item.action])(item.url,item.method);
							logger.debug('action',item.action,item.url);
							//console.log(mappings);
						})
					}else {
						if(!_.isObject(mappings)){
							throw new Error("error action mapping object.");
						}
						app[mappings.action](mappings.url,mappings.method);
						logger.debug('action',mappings.action,mappings.url);
					}
				}else{
					logger.warn(current.replace(__dirname,'') , 'not found mappings object.');
				}
			} else {
				//console.log(current,11);
				_load(current);
			}
		});
	}
	_load(config.app.actions_dir);
};